<?php
	namespace app\service\admin;
	use core\BaseService;
	use app\model\Article;
	use app\model\Label;
	use core\App;
	use core\Util;
	use app\model\ArticleLabel; 
	use app\model\ArticleUserRec;
	class ArticleService extends BaseService{
		function model(){
			return Article::$tableName;
		}
		function saveArticle($params,$info){
			$user = App::getCurrentUser();
			$labelArr= $params['label_id'];
			//记录标签
			$lData = $this->table(Label::$tableName)
				->whereIn('id',$labelArr)
				->select('id','name')->get();
			$params['label_json'] = json_encode($lData);
			if($params['id']){
				$pkId = $params['id'];
				$params = Article::filter($params);
				$params["edit_time"] = $time;
				$this->update($params);
				$info->success =true;
				$info->msg = '操作成功，数据已更新！';
			}else{
				$params = Article::filter($params);
				$time = Util::time();
				$params["create_time"] = $time;
				$params["edit_time"] = $time;
				$params['user_id'] = $user->id;
				$params['user_name'] = $user->login_name;
				$pkId = $this->insert($params,true);
				$info->success =true;
				$info->msg = '操作成功，数据已保存！';
			}
			
			if(!empty($labelArr)){
				//删除原有的标签
				$mTable = $this->table(ArticleLabel::$tableName);
				$mTable->where('article_id','=',$pkId)->delete();
				//更新标签
				$mTable = $this->table(ArticleLabel::$tableName);
				$datas = array();
				for($i=0;$i<count($labelArr);$i++){
					$datas[$i] = array(
						"article_id"=>$pkId,
						"label_id"=>$labelArr[$i]
					);
				}
				$mTable->insert($datas);
			}
		}

		function recArticle($id,$isRec,$info){
			$user = App::getCurrentUser();
			$mTable = $this->table(ArticleUserRec::$tableName);
			//先删出
			$mTable->where('article_id','=',$id)
				->where('user_id','=',$user->id)
				->delete();
			if($isRec){
				//重新添加
				$mTable = $this->table(ArticleUserRec::$tableName);
				$datas = array(
							"article_id"=>$id,
							"user_id"=>$user->id
				);
				$mTable->insert($datas);	
				$info->success = true;
				$info->msg = "已推荐成功！";
			}else{
				$info->success = true;
				$info->msg = "已取消推荐！";
			}
			//统计数量
			$count = $this->table(ArticleUserRec::$tableName)
				->where('article_id','=',$id)->count();
			$this->update(['id'=>$id,'rec_nums'=>$count]);
		}
	}